package cn.jaye.fabric.common.listener;

import cn.jaye.fabric.common.config.ApplicationContextProvider;
import cn.jaye.fabric.common.constants.FarbicConstant;
import cn.jaye.fabric.common.constants.TestConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/**
 * 动态数据源监听器
 *
 * @author Jaye
 * @create 2017-11-30 11:20
 */
@Component
public class AddPeerConfigListener implements ApplicationListener<AddPeerConfigEvent> {

    private final static Logger logger = LoggerFactory.getLogger(AddPeerConfigListener.class);

    @Autowired
    private ApplicationContextProvider applicationContextProvider;
    @Autowired
    private FarbicConstant farbicConstant;

//    @Autowired
//    private ClientService clientService;

    @Override
    public void onApplicationEvent(AddPeerConfigEvent addPeerConfigEvent) {
        updateConfig(addPeerConfigEvent.getPeerName(), addPeerConfigEvent.getOrgName());
    }

    public void updateConfig(String peerName, String orgName) {
//        GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
//        DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) applicationContextProvider.getApplicationContext().getAutowireCapableBeanFactory();
        TestConfig testConfig = (TestConfig) applicationContextProvider.getBean("testConfig");
        String org1 = testConfig.getProperty(testConfig.getINTEGRATIONTESTS_ORG() + "peerOrg1.peer_locations");
        StringBuffer org1PeerLocBuff = new StringBuffer(org1);
        org1PeerLocBuff.append(", " + peerName + ".org1.hna.com@grpc://" + farbicConstant.getHostAddress() + ":14051");
        testConfig.setProperty(testConfig.getINTEGRATIONTESTS_ORG() + "peerOrg1.peer_locations", org1PeerLocBuff.toString());

        String org1Even = testConfig.getProperty(testConfig.getINTEGRATIONTESTS_ORG() + "peerOrg1.eventhub_locations");
        StringBuffer org1EvenLocBuff = new StringBuffer(org1Even);
        org1EvenLocBuff.append(", " + peerName + ".org1.hna.com@grpc://" + farbicConstant.getHostAddress() + ":14053");
        testConfig.setProperty(testConfig.getINTEGRATIONTESTS_ORG() + "peerOrg1.eventhub_locations", org1EvenLocBuff.toString());

        testConfig.setSampleOrgs(testConfig.getSdkProperties());
        testConfig.setOrgCa();
//        clientService.setSampleOrgs(testConfig.getIntegrationTestsSampleOrgs());
    }

}
